package zheezes.protocol.impl.gd;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import zheezes.util.ArrayUtil;
import zheezes.util.ByteUtil;


public class Ctrl01Frame extends GdFrame {
    private byte[] tnm = new byte[8];
    private List<Short> dis = new ArrayList<Short>();
    
    public Ctrl01Frame() {
    	ctrl = 0x01;
	}

    public Ctrl01Frame(byte[] tnm) {
        this.ctrl = 0x01;
        System.arraycopy(tnm, 0, this.tnm, 0, 8);
    }

    public void addDataId(short di) {
        dis.add(di);
    }
    
    public int sizeOfData() {
    	return tnm.length + dis.size() * 2;
    }
    
    @Override
    public int getData(byte[] buf, int offset) {
		int idx = offset;
		System.arraycopy(tnm, 0, buf, idx, tnm.length);
		idx += tnm.length;
		for (Short di : dis) {
			ByteUtil.stoc(buf, idx, di);
			idx += 2;
		}
		return idx - offset;
	}

    @Override
    public int setData(byte[] buf, int offset, int max) {
        int idx = offset;
        System.arraycopy(buf, 0, tnm, 0, tnm.length);
        idx += tnm.length;
        while (idx < max) {
            dis.add(ByteUtil.ctos(buf, idx));
            idx += 2;
        }
        return 0;
    }

    public static void main(String[] args) {
        byte[] tnm = new byte[8];
        Arrays.fill(tnm, (byte) 0x00);
        Ctrl01Frame frm = null;
        GdConAddr rtua = new GdConAddr(0x82410001);
        GdMasterAddr msta = new GdMasterAddr((byte) 0x01);
        try {
            frm = new Ctrl01Frame(tnm);
            frm.setRtua(rtua);
            frm.setMsta(msta);
            frm.addDataId((short) 0x0102);
            System.out.println(ArrayUtil.sprintf(frm.getBytes(), "%02X "));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
